package com.example.springbootdemo.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.example.springbootdemo.model.CommonModel;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

// 登录拦截器
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI(); //获取URI
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        // springmvc 请求的时候会去检测协议协议
        if(uri.startsWith("/error")) {
            return true;
        }

        // 如果用户是去登录, 必须得有 username和password
        if(uri.startsWith("/login")) {
            if(StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
                writeErrorInfo(response, "参数错误");
                return false;
            }
            return true;
        }

        // 其他情况就要判断session中是否有数据
        HttpSession session = request.getSession();
        Object userInfo = session.getAttribute("userInfo");

        if(null == userInfo) {
            writeErrorInfo(response, "请登录");
            return false;
        }

        return true;
    }

    private void writeErrorInfo(HttpServletResponse response, String message) throws IOException {
        response.setContentType("application/json;charset=utf-8");
        CommonModel commonModel = new CommonModel();
        commonModel.setCode(-2);
        commonModel.setMsg(message);
        PrintWriter writer = response.getWriter();
        writer.write(JSONObject.toJSONString(commonModel));
        writer.flush();
        writer.close();
    }
}
